﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="PageTitle" runat="server">
    <title>考勤</title>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PageStyles" runat="server">
    <link href="../../Content/freecontent.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .fieldslist
        {
            word-break: break-all;
            word-wrap: break-word;
        }
        .expText
        {
            width: 280px;
        }
        #txtRemark
        {   
            font-size: 14px;
            width: 450px;
        }
        #txtRemark:hover
        {
            background-color: #FFFFAA;
        }
        #divRemark
        {
            margin-top: 10px;
            border-bottom: 1px solid #ccc;
        }
        .divEdit
        {
            margin-top: 10px;
            display: none;
            border-bottom: 1px solid #ccc;
        }
    </style>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="PageScripts" runat="server">
    <script src="../../Scripts/Attendance/attendance.js" type="text/javascript"></script>
    <script type="text/javascript">
    //************* URL常量
    var URL_APPLY_MODITY_ATTENDANCE_EVALUATION = "/Attendance/ApplyModifyAttendanceEvaluation";
    var URL_UPDATE_REMARK = "/Attendance/UpdateRemarkTheday";

    //************* 全局变量
    var g_Var = {
        "applyUserId": null,
        "time": null,
        "applicationWork": null
    };
    var Service = {};
    
    function InitService() {
        Service.DoUpdateRemark = $.AsyncMethod(URL_UPDATE_REMARK,"Post");
    }

    //************* 常量定义
    var StaticResource = {
        "ApplicationState": {
            "Applying": "您已申请修改考勤评估，等待处理中。",
            
        },
        "WeekendInfo": {
            "false": "非周末",
            "true": "周末"
        },
        "IsNeedToWork": {
            "false": "休息",
            "true": "正常上班"
        },
        "timeTarget": {
            "minute": "分钟",
            "hour": "小时"
        },

        "YesOrNoTarget": {
            "false": "否",
            "true": "是",
            "False": "否",
            "True": "是"
        },

        "ItemName": {
            "LateMiniutes": "迟到",
            "EarlyMiniutes": "早退",
            "IsAbsense": "旷工",
            "IsExtraWork": "加班",
            "ManHours": "获得工时"
        }

    };



    //************* Accessor访问器
    var EzAccessor = {};
    function CreateAccessor() {
            EzAccessor = CreateRealEzAccessor();
    }


    function CreateRealEzAccessor() {
        //实现服务器交互方法
        var realEzAccessor = {
            "getDayInfo": function () {
                                    return <%= ViewData["DayInfo"] %>;
            },
            "getIsDisplayAttendanceInfo": function () {
                                    return <%= ViewData["IsDisplayAttendanceInfo"] %>;
            },
            "getIsDisplayApplyEvaluation": function () {

                                    return <%= ViewData["IsDisplayApplyEvaluation"]%>;
            }, 
            "getIsDisplayEvaluationInfo": function () {

                                    return <%= ViewData["IsDisplayEvaluationInfo"]%>;
            },
            "getIsApplyingModify": function () {

                                    return <%= ViewData["IsApplyingModify"]%>;
            },
            "getEvaluationModifyApplications": function () {
                                    return <%= ViewData["ModifyAttendanceApplication"] %>;
            },
            "getTargetUser": function () {
                                    return <%= ViewData["TargetUser"]%>

            },

            "getDayAttendanceDetail": function () {
                                    return <%= ViewData["DayAttendanceDetail"] %>;
            },

            "geEvaluationModifyHistory": function () {
                                    return <%= ViewData["EvaluationModifyHistory"] %>;
            },

            "doApplyModify": function (applyUserId, date, applyText) {
                $.post(
                    URL_APPLY_MODITY_ATTENDANCE_EVALUATION,
                    {
                        'applyUserId': applyUserId,
                        'date': date,
                        'applyText': applyText
                    },
                    function (e) {
                        if (e.Status == "Success") {
                            var url = '/Attendance/PersonalAttendanceInfoPerDay?time={time}';
                            url = url.replace("{time}", date);
                            $.redirectAndDisplayInfo(url, e);
                        } else {
                            $.displayStatusInfo(e);
                        }
                    }
                );
            }
        };

        return realEzAccessor;
    }

    function getIsRemarkEmpty(){
        var isRemarkEmpty = false;
        if($('#txtRemark').html() == "单击此处添加考勤备注"){
            isRemarkEmpty = true;    
        }

        return isRemarkEmpty;
    }

    function bindRemark(remarkInfo){
        var remark = remarkInfo? remarkInfo.Remark : "";
        
        if(remark.htmlEncode().trim() !=  ""){
            $('#txtRemark').html(remark);
        }   
        else {
            $('#txtRemark').html('单击此处添加考勤备注');
        } 
    }

    //上下班打卡考勤记录
    function bindCheckAttendanceDetail(attendanceInfoList) {
        var ondutyNum = 0;
        var offdutyNum = 0;
        for (var key in attendanceInfoList) {
            var actionTime = Date.fromEpoch(attendanceInfoList[key].ActionTime).toFullTimeFormat();
            var isAbnormal = attendanceInfoList[key].IsAbnormalAttendance ? '<span class="important">*</span>' : "";
            var explanation = attendanceInfoList[key].Explanation;
            var explanationStr = (explanation == null)? "" : explanation; 
            var attendanceDom = '<p>{isAbnormal}{actionTime}</p><p class="expText">{Explanation}</p>';
            attendanceDom = attendanceDom.replace("{actionTime}", actionTime)
                                         .replace("{isAbnormal}", isAbnormal)
                                         .replace("{Explanation}", explanationStr);
            //上班
            if (attendanceInfoList[key].AttendanceType == "onDuty") {
                $('#actionTimeOnDuty').append(attendanceDom);
                ondutyNum = ondutyNum + 1;
            }
            //下班
            else {
                $('#actionTimeOffDuty').append(attendanceDom);
                offdutyNum = offdutyNum + 1;
            }
        }
        //没用考勤记录的处理
        if(ondutyNum == 0){
            $('#actionTimeOnDuty').append('<small>没有考勤记录</small>');     
        }
        if(offdutyNum == 0){
            $('#actionTimeOffDuty').append('<small>没有考勤记录</small>');  
        }

    }


    //假期信息
    function bindLeaveInfoDetail(leaveList) {
        if (leaveList) {
            var leaveInfo = leaveList.Leaves;
            if (leaveInfo.length == 0) {
                $('#cmbLeaveInfo').parent().parent().remove();
            }
            for (var key in leaveInfo) {
                var leaveName = leaveInfo[key].LeaveTypeName;
                var startTime = Date.fromEpoch(leaveInfo[key].StartTime);
                var endTime = Date.fromEpoch(leaveInfo[key].EndTime);
                var startTimeFormat = startTime.toFullTimeFormat();
                var endTimeFormat = endTime.toFullTimeFormat();
                var leaveTime = startTimeFormat + " 至 " + endTimeFormat;
                var leaveInfoDom = '<p>{leaveName} {leaveTime}</p>';


                leaveInfoDom = leaveInfoDom.replace("{leaveName}", leaveName)
                                           .replace("{leaveTime}", leaveTime);

                $('#cmbLeaveinfo').append(leaveInfoDom);

            }
        }
    }



    //考勤评估信息
    function bindAttendanceEvaluationDetail(attendanceEvaluation) {
        if (attendanceEvaluation) {
            var lateMiniute = attendanceEvaluation.LateMiniutes;
            var earlyMiniutes = attendanceEvaluation.EarlyMiniutes;
            var isAbsense = StaticResource.YesOrNoTarget[attendanceEvaluation.IsAbsense];
            var isExtraWork = StaticResource.YesOrNoTarget[attendanceEvaluation.IsExtraWork];
            var manHours = toManHours(attendanceEvaluation.Manhours);

            $('#cmbBeLate').html(lateMiniute + StaticResource.timeTarget.minute);
            $('#cmbLeaveEarly').html(earlyMiniutes + StaticResource.timeTarget.minute);
            $('#cmbAbsent').html(isAbsense);
            $('#cmbExtraWork').html(isExtraWork);
            $('#cmbManHours').html(manHours + StaticResource.timeTarget.hour);
        }
    }



    function bindAttendanceDetail(attendanceDetail, IsDisplayEvaluationInfo) {
        bindCheckAttendanceDetail(attendanceDetail.AttendanceEvaluation.DayAttendanceInfoList);
        bindLeaveInfoDetail(attendanceDetail.AttendanceEvaluation.LeaveInfo);
        
        bindRemark(attendanceDetail.RemarkInfo);

        if (IsDisplayEvaluationInfo) {
            bindAttendanceEvaluationDetail(attendanceDetail.AttendanceEvaluation);
        }else{
            $('#attendaceEvl').hide();
        }
    }




   
    //修改记录
    function showEvaluationModifyHistory(evaluationModifyHistory) {
        if(evaluationModifyHistory){
            for (var key in evaluationModifyHistory) {
                var evaluationChange = $('<div class="evaluationChange"></div>');
                var modifyOn = Date.fromEpoch(evaluationModifyHistory[key].ModifyOn);
                var modifyOnFormat = modifyOn.toShortDateTime();
                var operatorName = evaluationModifyHistory[key].Operator.Name;
                //修改人和修改时间
                var modifyTittle = '<p style="margin-top:10px;">{operatorName} 在 {modifyOnFormat}</p>';
                modifyTittle = modifyTittle.replace("{operatorName}", operatorName)
                                           .replace("{modifyOnFormat}", modifyOnFormat);

                //修改内容
                var modifyInfo = '';
                var attendanceEvaluationChangeList = evaluationModifyHistory[key].EvaluationChangeItem;
                
                for (var target in attendanceEvaluationChangeList) {
                    var itemName = StaticResource.ItemName[attendanceEvaluationChangeList[target].ItemName];
                    var oldValue = attendanceEvaluationChangeList[target].OldValue;
                    var newValue = attendanceEvaluationChangeList[target].NewValue;

                    //时间单位是分钟还是小时
                    //加班和旷工项  对true 和 false的处理
                    oldValue = editEvaluationItemValue(itemName, oldValue);
                    newValue = editEvaluationItemValue(itemName, newValue);

                    modifyInfo = modifyInfo + '<p>将 {itemName} {oldValue} 修改为 {newValue}</p>';
                    modifyInfo = modifyInfo.replace("{itemName}", itemName)
                                            .replace("{oldValue}", oldValue)
                                            .replace("{newValue}", newValue);

                }
                if (attendanceEvaluationChangeList.length == 0) {
                    modifyInfo = '<p>拒绝了考勤评估修改申请。</p>';
                }
                $(evaluationChange).append(modifyTittle)
                                   .append(modifyInfo);
                $("#cmbEvaluationModifyHistory").append(evaluationChange);
            }
            
            
            $('tip_ModifyInfo').eztips();
            
            $('.evaluationChange:first-child').find('p').css({'color': '#008B00'});
        }
    }




    function showApplicationList(application) {
        if(application) {
            var applyUserName = application.ApplyUser.Name;
            var applyOn = Date.fromEpoch(application.ApplyOn);
            var applyOnFormat = applyOn.toShortDateTime();
            var applyText = application.ApplyText;
            var applyState = application.State;

            if(applyState == "Applying"){
                $('#txtWarn').html(StaticResource.ApplicationState.Applying);
                $('#txtWarn').css({
                                    'font-size': '16px',
                                    'font-weight':'bold',
                                    'color': 'red'
                                 });
            }

            var applyInfoDom = '<p><span>{applyUserName} 于 {applyOn} 申请</span></p><p> 修改原因： <span >{applyText}</span></p>';
            applyInfoDom = applyInfoDom.replace("{applyUserName}", applyUserName)
                                        .replace("{applyOn}", applyOnFormat)
                                        .replace("{applyText}", applyText);
                                        
            $('#cmbApplyInfo').append(applyInfoDom);
            $('#tipApplyInfo').eztips();
            
        }

    }
    //显示当日信息
    function showDayInfo(dayInfo) {
        var isWeekEnd = StaticResource.WeekendInfo[dayInfo.IsWeekEnd];
        var needToWork = StaticResource.IsNeedToWork[dayInfo.IsNeedToWork];
        var extraShiftInfo = "";
        var holidayInfo = "";
        if (dayInfo.ExtraShiftInfo && dayInfo.HolidayInfo) {
            extraShiftInfo = dayInfo.ExtraShiftInfo.Name
            holidayInfo = dayInfo.HolidayInfo.Name;
        }

        var dayInfoDom = '<p>当日信息 : {weekendInfo}  {holidayInfo}  {extraShiftInfo} {needToWork}</p>';
        dayInfoDom = dayInfoDom.replace("{weekendInfo}", isWeekEnd)
                               .replace("{holidayInfo}", holidayInfo)
                               .replace("{extraShiftInfo}", extraShiftInfo)
                               .replace("{needToWork}", needToWork);

        $('#lblDayInfo').append(dayInfoDom);
    }




    //Tittle
    function showApplicationTittle(currentUser, dayInfo) {
        var applyUserName = currentUser.Name;
        var nowDay = Date.fromEpoch(dayInfo.Date).toFullChineseDateFormat();
        var tittleStr = applyUserName + " " + nowDay + " " + "考勤详细情况";

        $('#lblTittle').html(tittleStr);
    }



    function editEvaluationItemValue(itemName, value) {
        var editedValue = value + StaticResource.timeTarget.minute;
        switch (itemName) {
            case StaticResource.ItemName.ManHours: editedValue = toManHours(value) + StaticResource.timeTarget.hour;
                break;
            case StaticResource.ItemName.IsExtraWork: editedValue = StaticResource.YesOrNoTarget[value];
                break;
            case StaticResource.ItemName.IsAbsense: editedValue = StaticResource.YesOrNoTarget[value];
                break;

        }

        return editedValue;

    }



   

    function showApplicationDetail(dayInfo, targetUser) {

        showDayInfo(dayInfo);
        showApplicationTittle(targetUser, dayInfo);
    }



    function initPage() {
        InitService();
        $('#tip_Remind').eztips();
       
        //获取数据
        CreateAccessor();

        var dayInfo = EzAccessor.getDayInfo();
        var isDisplayAttendanceInfo = EzAccessor.getIsDisplayAttendanceInfo();
        var targetUser = EzAccessor.getTargetUser();

        g_Var["time"] = dayInfo.Date;
        g_Var["applyUserId"] = targetUser.Id;

        //显示当日信息，申请信息，评估历史等
        showApplicationDetail(dayInfo, targetUser);

        if (isDisplayAttendanceInfo) {
            var application = EzAccessor.getEvaluationModifyApplications();
            var isDisplayApplyEvaluation = EzAccessor.getIsDisplayApplyEvaluation();
            var attendanceDetail = EzAccessor.getDayAttendanceDetail();
            var evaluationModifyHistory = EzAccessor.geEvaluationModifyHistory();
            var IsDisplayEvaluationInfo = EzAccessor.getIsDisplayEvaluationInfo();
            var IsApplyingModify = EzAccessor.getIsApplyingModify();
            //已存在申请
            showApplicationList(application);
            //修改历史
            showEvaluationModifyHistory(evaluationModifyHistory);
            //考勤信息
            bindAttendanceDetail(attendanceDetail, IsDisplayEvaluationInfo);
            //是否可以申请修改
            if (!isDisplayApplyEvaluation) {
                $('#applyModify').hide();
            }else{
                $('#applyModify').show();
            }

            //未来时间不可查看
            if(!IsDisplayEvaluationInfo){
                $('#nextDay').hide();    
            }
            //是否正在申请
            if(IsApplyingModify){
                showApplyContent();
            }
        }
        else {
            $('#tblNoFuture').show();
            $('#nextDay').hide();
            $('#preDay').hide();
            $('#tblAttendanceInfo').hide();
        }

    }

    function  showApplyContent() {
        var divDom = $("<div/>");
        var htmlText = '<p>请填写申请修改考勤评估的原因:</p>' +
                        '<textarea cols="43" rows="4" id="txtExplain"></textarea>' +
                        '<div>' +
                                '<div id="btnSubmit" style="width: 80px; height: 30px;">确定</div>' +
                        '</div>';

        $(divDom).html(htmlText);
        $(divDom).find("#btnSubmit")
                .button({
                    icons: {
                        primary: "ui-icon-circle-arrow-n"
                    },
                    text: true
                });;

        divDom.dialog(
        {   
            modal: true,
            width: 460,
            height: 200,
            resizable: false,
        });

        $('#txtExplain').focus();
        //确定申请
        $('#btnSubmit').click(function () {
            var applyUserId = g_Var["applyUserId"];
            var date = g_Var["time"];
            var applyText = $('#txtExplain').val().htmlEncode();

            EzAccessor.doApplyModify(applyUserId, date, applyText);
        });

    }

    function initPageEvent() {

        //申请修改
        $('#applyModify').click(function () {
            showApplyContent();
        });


        $('#preDay').click(function () {
            var date = Date.fromEpoch(g_Var["time"]);

            var perDay = new Date(
                date.getFullYear(),
                date.getMonth(),
                date.getDate() - 1,
                0,
                0,
                0
            ).toEpoch();

            window.location.href = "PersonalAttendanceInfoPerDay?time="
                           + perDay;

        });


        $('#nextDay').click(function () {
            var date = Date.fromEpoch(g_Var["time"]);

            var nextDay = new Date(
                date.getFullYear(),
                date.getMonth(),
                date.getDate() + 1,
                0,
                0,
                0
            ).toEpoch();

            window.location.href = "PersonalAttendanceInfoPerDay?time=" + nextDay;

        });

        $('#btn-return-attendancelist').click(function (){
            window.location.href = '/Attendance/PersonalAttendanceInfoList?time=' + g_Var["time"];
        });


        $('#txtRemark').click(function (){
            $(this).hide();
            $('.divEdit').show();

            if(getIsRemarkEmpty() == false) {
                $('#template').val($('#txtRemark').html().htmlEncode().trim());    
            }
            $('#template').select();
        });

        $('#btnCancelRemark').click(function (){
            $('#template').clearFields();
            $('#txtRemark').show();
            $('.divEdit').hide();
        });

        $('#btnSumbit').click(function (){
            $('#txtRemark').show();
            $('.divEdit').hide();
            //提交
            var remark = $('#template').val().htmlEncode().trim();
            if(remark != "") {
                Service.DoUpdateRemark( function (e) {
                    $.displayStatusInfo(e);

                    if(remark == ""){
                        $('#txtRemark').html("单击此处添加考勤备注");
                    }else{
                        $('#txtRemark').html(remark);
                    }
                }, {userId: g_Var.applyUserId, time: g_Var.time, remark: remark});
            }
        });


    }

    $(function () {
        initPage();
        initPageEvent();
    });
    </script>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="PageHead" runat="server">
    <%
        Html.RenderPartial("_sayHello"); %>
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="PageContent" runat="server">
    <div id="page-head" class="page-head">
        <img src="../../Content/icons/attendance_perday.png" style="width: 48px; height: 48px;"
            alt="personalPerday" />
        <span id="lblTittle" class="title"></span>
        <div style="margin-top: 5px; min-height: 20px;">
            <div style="float: left;">
                <a id="preDay">前一天</a>
            </div>
            <div style="float: right;">
                <a id="nextDay">后一天</a>
            </div>
        </div>
    </div>
    <div id="page-body">
        <div id="tblNoFuture" style="display: none;">
            <%Html.RenderPartial("_noFutureDisplayInfo"); %>
        </div>
        <div id="divRemark">
            <p id="txtRemark">
            </p>
        </div>
        <div class="divEdit">
            <textarea id="template" cols="40" rows="5" style="margin-bottom: 10px;"></textarea>
            <div style="margin-bottom: 10px;">
                <div id="btnSumbit">提交</div>
                <script type="text/javascript">
                    $(function () {
                        $("#btnSumbit").button({
                            icons: {
                                primary: "ui-icon-circle-arrow-n"
                            },
                            text: true
                        });
                    });
                </script>
                &nbsp;或者&nbsp;<a id="btnCancelRemark">取消</a>
            </div>
        </div>
        <div id="attendaceEvl" style="margin-top: 10px;">
            <p class="entry-explanation">
                考勤评估记录</p>
            &nbsp;<span id="txtWarn">如果您的考勤评估信息与实际情况存在出入,或者因为其他原因,可以申请修改相应信息。</span>
            <br />
            <a id="applyModify"  style="display: none;">申请修改考勤评估</a>
            <script type="text/javascript">
                $(function () {
                    $("#applyModify").button({
                        icons: {
                            primary: "ui-icon-pencil"
                        },
                        text: true
                    });
                });
        </script>
            <div style="border: 1px solid #090; margin-top: 10px;">
                <ul class="fieldslist">
                    <li>
                        <div class="l">
                            迟到：
                        </div>
                        <div class="r">
                            <p id="cmbBeLate">
                            </p>
                        </div>
                    </li>
                    <li>
                        <div class="l">
                            早退：
                        </div>
                        <div class="r">
                            <p id="cmbLeaveEarly">
                            </p>
                        </div>
                    </li>
                    <li>
                        <div class="l">
                            旷工：</div>
                        <div class="r">
                            <p id="cmbAbsent">
                            </p>
                        </div>
                    </li>
                    <li>
                        <div class="l">
                            加班：</div>
                        <div class="r">
                            <p id="cmbExtraWork">
                            </p>
                        </div>
                    </li>
                    <li>
                        <div class="l">
                            工时：
                        </div>
                        <div class="r">
                            <p id="cmbManHours">
                            </p>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
        <div id="tblAttendanceInfo" style="margin-top: 10px;">
            <p class="entry-explanation">
                考勤记录</p>
            &nbsp;<span>当日上下班考勤记录。</span>
            <div>
                <ul class="fieldslist">
                    <li>
                        <div class="l">
                            上班：
                        </div>
                        <div id="actionTimeOnDuty" class="r">
                        </div>
                    </li>
                    <li>
                        <div class="l">
                            下班：
                        </div>
                        <div id="actionTimeOffDuty" class="r">
                        </div>
                    </li>
                </ul>
                <ul class="fieldslist">
                    <li>
                        <div class="l">
                        </div>
                        <div id="cmbLeaveinfo" class="r">
                        </div>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <div class="page-submit" style="display: none;">
        <div style="margin: 20px 20px 30px 30px;">
            <div class="formBox">
            </div>
        </div>
    </div>
</asp:Content>
<asp:Content ID="Content6" ContentPlaceHolderID="PageShortcut" runat="server">
    <div id="shortcuts" class="box">
        <a style="width:100%;" id="btn-return-attendancelist">返回考勤列表 </a>
        <script type="text/javascript">
            $(function () {
                $("#btn-return-attendancelist").button({
                    icons: {
                        primary: "ui-icon-arrowreturnthick-1-w"
                    },
                    text: true
                });
            });
        </script>
    </div>
</asp:Content>
<asp:Content ID="Content7" ContentPlaceHolderID="PageFoot" runat="server">
    <div id="tip_Remind" style="display: none;">
        <h1>
            小贴士:</h1>
        <p class="indent">
        </p>
    </div>
    <div id="tip_ApplyInfo" style="display: none;" class="tip-succ">
        <h1>
            考勤评估修改申请:</h1>
        <div id="cmbApplyInfo" class="indent">
        </div>
    </div>
    <div id="tip_ModifyInfo" style="display: none;" class="tip-memo">
        <h1>
            考勤评估修改历史:</h1>
        <div id="cmbEvaluationModifyHistory" class="indent">
        </div>
    </div>
    <div id="popContent" style="display: none;">
    </div>
</asp:Content>
